from osgeo import gdal
import os
from base.base import get_coord_by_index, get_tile_size

# 对应自己的python包的安装地址
os.environ[
    'PROJ_LIB'] = r'C:\Users\Administrator\AppData\Local\Programs\Python\Python39\Lib\site-packages\pyproj\proj_dir\share\proj'


def to_tiff(base_path, x, y, z, x_tile_count):
    print("转换格式")
    dataset = gdal.Open(base_path)
    band_count = dataset.RasterCount
    cols = dataset.RasterXSize  # 列数
    rows = dataset.RasterYSize  # 行数
    print(band_count, rows, cols)
    result_path = base_path[0:base_path.rfind(".")] + ".tiff"

    img_proj = '''PROJCS["WGS 84 / Pseudo-Mercator",
        GEOGCS["WGS 84",
            DATUM["WGS_1984",
                SPHEROID["WGS 84",6378137,298.257223563,
                    AUTHORITY["EPSG","7030"]],
                AUTHORITY["EPSG","6326"]],
            PRIMEM["Greenwich",0,
                AUTHORITY["EPSG","8901"]],
            UNIT["degree",0.0174532925199433,
                AUTHORITY["EPSG","9122"]],
            AUTHORITY["EPSG","4326"]],
        PROJECTION["Mercator_1SP"],
        PARAMETER["central_meridian",0],
        PARAMETER["scale_factor",1],
        PARAMETER["false_easting",0],
        PARAMETER["false_northing",0],
        UNIT["metre",1,
            AUTHORITY["EPSG","9001"]],
        AXIS["X",EAST],
        AXIS["Y",NORTH],
        EXTENSION["PROJ4","+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs"],
        AUTHORITY["EPSG","3857"]]'''
    red = dataset.GetRasterBand(1)

    target_ds = gdal.GetDriverByName('GTiff').Create(result_path, xsize=cols, ysize=rows, bands=3,
                                                     eType=red.DataType)

    target_ds.SetProjection(img_proj)
    for i in range(1, 4):
        band = dataset.GetRasterBand(i).ReadAsArray(0, 0, cols, rows)
        target_ds.GetRasterBand(i).SetNoDataValue(0)
        target_ds.GetRasterBand(i).WriteArray(band)
    # 左上角坐标
    origin = get_coord_by_index(x, y, z)
    print(origin)
    scale = get_tile_size(z) * x_tile_count / cols
    target_ds.SetGeoTransform([origin[0], scale, 0, origin[1], 0, -scale])
    target_ds.FlushCache()
    print(scale)
    del dataset
    return result_path


if __name__ == '__main__':
    to_tiff(r'E:\FFOutput\res1.png', 0, 0, 4, 16)
